﻿#include <QJsonDocument>
#include <QJsonObject>
#include <QElapsedTimer>

#include "SerialPortSendReplyClient.h"
#include "apputils.h"
SerialPortSendReplyClient::SerialPortSendReplyClient()
{

}

bool SerialPortSendReplyClient::Connect()
{
    return _serial->open(QIODevice::ReadWrite);
}

void SerialPortSendReplyClient::SetCommunicationParam(QString communicationParam)
{
    QMap<QString,QSerialPort::Parity> parityMap={
        {"NoPraity",QSerialPort::NoParity},
        {"EvenParity",QSerialPort::EvenParity},
        {"OddParity",QSerialPort::OddParity},
        {"SpaceParity",QSerialPort::SpaceParity},
        {"MarkParity",QSerialPort::MarkParity}
    };
    QMap<QString,QSerialPort::DataBits> dataMap={
        {"Data5",QSerialPort::Data5},
        {"Data6",QSerialPort::Data6},
        {"Data7",QSerialPort::Data7},
        {"Data8",QSerialPort::Data8}
    };
    QMap<QString,QSerialPort::StopBits> stopMap={
        {"OneStop",QSerialPort::OneStop},
        {"OneAndHalfStop",QSerialPort::OneAndHalfStop},
        {"TwoStop",QSerialPort::TwoStop}
    };

    BaseCommunication::SetCommunicationParam(communicationParam);
    QJsonObject obj=QJsonDocument::fromJson(communicationParam.toUtf8()).object();
    _serial=new QSerialPort();
    connect(_serial,&QSerialPort::errorOccurred,this,&SerialPortSendReplyClient::OnError);
    connect(_serial,&QSerialPort::readyRead,this,&SerialPortSendReplyClient::OnReadyReady);
    _serial->setPortName(obj["PortName"].toString());
    _serial->setParity(parityMap[obj["Parity"].toString()]);
    _serial->setBaudRate(obj["BaudRate"].toInt());
    _serial->setDataBits(dataMap[obj["DataBits"].toString()]);
    _serial->setStopBits(stopMap[obj["StopBits"].toString()]);
    _serial->setFlowControl(QSerialPort::NoFlowControl);  //无流控制
    _serial->setReadBufferSize(1000);
}

void SerialPortSendReplyClient::Dispose()
{
    _serial->close();
    _serial->deleteLater();
}

bool SerialPortSendReplyClient::SendReply(QByteArray sendBuff, QByteArray &receiveBuff)
{
    _recList.clear();
    _serial->write(sendBuff);

    QElapsedTimer ela;
    ela.start();
    while(_recList.count()==0)
    {
        AppUtils::WaitMs(100,false);
        if(ela.elapsed()>3000)
        {
            throw QString("%1 time out").arg(_name);
        }
    }
    AppUtils::WaitMs(50,false);
    QByteArray arr;
    for(int i=0;i<_recList.count();i++)
    {
        arr.append(_recList.at(i));
    }
    receiveBuff=arr;
    return true;
}

bool SerialPortSendReplyClient::SendNoReply(QByteArray sendBuff)
{
    _recList.clear();
    return  _serial->write(sendBuff)!=-1;
}

void SerialPortSendReplyClient::OnError(QSerialPort::SerialPortError err)
{
    qDebug()<<__FUNCTION__<<__LINE__<<_name<<err<<_serial->errorString();
}

void SerialPortSendReplyClient::OnReadyReady()
{
    _recList.append(_serial->readAll());
}
